<template>
  <div>
    <el-card>
      <!-- class="project-list-container" -->
      <div>
        <div class="list-h">
          <el-button
            type="primary"
            v-auth="`/project/manage-add`"
            @click="handleAdd"
            class="add-option"
            >创建项目</el-button
          >
          <el-form
            :inline="true"
            class="demo-form-inline"
            :model="formInline"
            ref="formRef"
            @submit.prevent
          >
            <el-form-item label="项目名称" prop="projectNameLike">
              <el-input
                v-model.trim="formInline.projectNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="项目编号" prop="projectCodeLike">
              <el-input
                v-model.trim="formInline.projectCodeLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属公司主体" prop="principalCompanyCodeIn">
              <el-select v-model="formInline.principalCompanyCodeIn">
                <el-option label="华润啤酒" value="1,2,3,4,5,6" />
                <el-option label="华润雪花" value="2" />
                <el-option label="华润酒业" value="3,4,5,6" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建人" prop="createUserNameLike">
              <el-input
                v-model.trim="formInline.createUserNameLike"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="项目类型" prop="projectTypeCode">
              <el-select
                v-model="formInline.projectTypeCode"
                clearable
                class="width-custom120"
              >
                <el-option
                  v-for="item in projectTypeArr"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item.dicCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                class="width-custom220"
                v-model="createTime"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleChangeDate"
              />
            </el-form-item>
            <!-- <el-form-item label="审批状态" prop="flowStatus">
              <el-select
                v-model="formInline.flowStatus"
                clearable
                class="width-custom120"
              >
                <el-option
                  v-for="item in flowStatusArr"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item.dicCode"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <!-- <el-button type="primary" @click="handleAdvancedSearch"
                >高级搜索</el-button
              > -->
            </el-form-item>
          </el-form>
        </div>
        <div class="list-h" v-if="isSearch">
          <div class="add-option"></div>
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="文档名称" prop="documentName">
              <el-input
                v-model.trim="formInline.documentName"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>

            <el-form-item label="文档类型" prop="documentType">
              <el-select
                v-model="formInline.documentType"
                filterable
                class="width-custom120"
              >
                <el-option
                  v-for="item in documentTypes"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item.dicCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="成果来源" prop="achievementType">
              <el-select
                v-model="formInline.achievementType"
                filterable
                class="width-custom120"
              >
                <el-option
                  v-for="item in achievementTypes"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item.dicCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="评审专家" prop="expertName">
              <el-input
                v-model.trim="formInline.expertName"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
            <el-form-item label="费用科目" prop="costName">
              <el-input
                v-model.trim="formInline.costName"
                clearable
                class="width-custom120"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>

        <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <el-table-column type="index" label="序号" width="60">
              <template v-slot="scope">
                <span>{{
                  (formInline.pageNum - 1) * formInline.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="projectCode"
              label="项目编号"
            ></el-table-column>
            <el-table-column
              prop="projectName"
              label="项目名称"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="projectTypeName"
              label="项目类型"
            ></el-table-column>
            <el-table-column label="项目审批类别">
              <template #default="{ row }">
                <span
                  >{{ row.approveTypeMaxName }}-{{
                    row.approveTypeMinName
                  }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="createUserName"
              label="创建人"
            ></el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              :min-width="120"
            ></el-table-column>
            <el-table-column label="项目阶段">
              <template #default="{ row }">
                {{ stages[row.stageStatus] }}
              </template>
            </el-table-column>

            <el-table-column prop="" label="项目状态">
              <template #default="{ row }">
                {{ formatterStatusType(row) }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="" label="项目阶段状态">
              <template #default="{ row }">
                {{ formatterStatusType2(row) }}
                <a
                  style="color: #f89c34"
                  v-if="row.stageApproveStatus === '4'"
                  @click="alertMsg(row)"
                  >驳回原因</a
                >
              </template>
            </el-table-column> -->
            <!-- <el-table-column
              show-overflow-tooltip
              label="项目进展"
              prop="currentProgress"
            >
            </el-table-column> -->

            <el-table-column label="操作" width="240" fixed="right">
              <template #default="{ row }">
                <!-- <el-button type="text" @click="handProgressDesc(row)"
                  >项目进展</el-button
                > -->
                <el-button
                  type="text"
                  v-if="+row.saveStatus > 1 && row.saveStatus !== '4'"
                  @click="handleLook(row)"
                  >查看
                </el-button>
                <!-- (row.saveStatus === '3' && row.stageStatus === '0') || -->
                <el-button
                  v-if="getEditAuth(row)"
                  type="text"
                  @click="handleEdit(row, 'edit')"
                  >编辑</el-button
                >

                <!-- canAdminProcess：管理员，stageApproveStatus：第二次审批，stageStatus：建档阶段 -->

                <!--
                <el-button
                  v-if="
                    row.saveStatus &&
                    getAtch(row) &&
                    row.stageStatus === '0' &&
                    row.stageApproveStatus != '2' &&
                    row.canAdminProcess != 1
                  "
                  type="text"
                  @click="handleEdit(row, 'approval')"
                  >审核</el-button
                >
                <el-button
                  v-if="
                    row.stageStatus === '0' &&
                    row.stageApproveStatus === '2' &&
                    row.canAdminProcess === 1 &&
                    getAtch(row)
                  "
                  type="text"
                  @click="handleEdit(row, 'approval')"
                  >审核</el-button
                > -->

                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button v-auth="`/project/manage-del`" type="text"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-skeleton>
      </div>
      <re-pagination
        :total="total"
        v-show="total > 0"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleSearch"
      />
    </el-card>
  </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref, defineComponent } from "vue";
import {
  postProjectList,
  postProjectDelete,
  updateProgress,
  postProjecStop
} from "/@/api/project";
import { postDictList } from "/@/api/common";
import NotifMessage from "/@/utils/message/notification";
import { useRouter } from "vue-router";
import { ProjectStatusMap2 } from "../types";
import { ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash-es";
import { storageLocal } from "/@/utils/storage";
// import { useProjectStoreHook } from "/@/store/modules/project";
export default defineComponent({
  name: "UserManage",
  components: {},
  setup() {
    const router = useRouter();
    const formRef = ref<HTMLFormElement | null>(null) as any;

    let loading = ref<boolean>(false);
    let projectStep = ref<Array<any>>([]);
    let total = ref<number>(0);
    let progressDesc = ref<string>("");
    let formInline = reactive<any>({
      principalCompanyCodeIn: "1,2,3,4,5,6",
      isFilings: "1",
      projectNameLike: "",
      projectCodeLike: "",
      createUserNameLike: "",
      projectTypeCode: "",
      stageStatusUpper: "0",
      documentName: "",
      documentType: "",
      achievementType: "",
      expertName: "",
      costName: "",
      createTimeStrStart: "",
      createTimeStrEnd: "",
      // stageStatus: "0",
      flowStatus: "",
      pageSize: 10,
      pageNum: 1
    });

    let state = reactive({
      projectId: "",
      createTime: "",
      stages: ["建档 ", "可研", "立项", "实施", "验收", "后评价", "项目已结束"],

      stopDialogFormVisible: false,
      isSearch: false,
      target: null,
      documentTypes: [
        { dicCode: "0", dicValue: "项目文件" },
        { dicCode: "1", dicValue: "支撑材料" },
        { dicCode: "2", dicValue: "费用账目" },
        { dicCode: "3", dicValue: "公共信息" },
        { dicCode: "4", dicValue: "文件模板" }
      ],
      achievementTypes: [
        { dicCode: "0", dicValue: "专利" },
        { dicCode: "1", dicValue: "软件著作权" },
        { dicCode: "2", dicValue: "论文" },
        { dicCode: "3", dicValue: "专著" },
        { dicCode: "4", dicValue: "标准" },
        { dicCode: "5", dicValue: "科技奖励" },
        { dicCode: "6", dicValue: "科技制度建设" },
        { dicCode: "7", dicValue: "合作单位" },
        { dicCode: "8", dicValue: "其他" }
      ],
      tableData: [],
      companyInfo: {}
    });

    let projectTypeArr = ref([]);
    let flowStatusArr = ref([]);

    const handleChangeDate = time => {
      formInline.createTimeStrStart = time[0];
      formInline.createTimeStrEnd = time[1];
    };

    // stageStatus:项目阶段   (0：建档 1：可研、2：立项、3：实施、4：验收、5：后评价)
    // saveStatus:保存状态    (1保存、2提交 3、已审核 4、驳回 5、变更中 6、终止申请中 7、已终止 8、变更驳回)
    // stageApproveStatus:阶段流转状态    (1、未提交 2、提交流转 3、已审核 4、驳回)
    // canProcess是否可以审核(阶段流转提交)    0:否，1：是
    // canAuth是否可以审核(草稿项目提交)       0:否，1：是
    // canAdminProcess建档阶段只有管理员可以审核(阶段流转提交)  0:否，1：是
    const getEditAuth = row => {
      return (
        +row.stageStatus < 3 &&
        row.projectApproveStatus === "1" &&
        row.createUser == storageLocal.getItem("rdms-info")?.userId
      );
      // return (
      //   row.saveStatus === "1" || //建档项目状态为草稿
      //   ((row.stageStatus === "0" || row.stageStatus === "2") &&
      //     row.saveStatus === "3" &&
      //     (row.stageApproveStatus === "4" || row.stageApproveStatus === "1")) || //项目阶段为建档、项目状态为已审核、项目阶段状态为驳回
      //   (row.stageStatus === "0" && row.projectApproveStatus === "1") ||
      //   row.stageStatus === "1" ||
      //   row.stageStatus === "2" ||
      //   (row.saveStatus === "8" &&
      //     (row.stageStatus === "0" || row.stageStatus === "2")) //建档项目状态为驳回
      // );
    };

    const getChangeAuth = row => {
      // console.log(+row.stageStatus > 2);
      return (
        +row.stageStatus > 2 &&
        row.stageStatus !== "6" &&
        row.saveStatus !== "6" &&
        row.saveStatus !== "5" &&
        (row.stageApproveStatus === "4" || row.stageApproveStatus === "1")
      );
    };

    // 请求公司列表表格数据
    async function getTableData() {
      // 真实请求待添加
      loading.value = true;
      try {
        let copyParams = cloneDeep(formInline);
        copyParams.principalCompanyCodeIn =
          copyParams.principalCompanyCodeIn.split(",");
        const { code, data } = await postProjectList(copyParams);
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    }
    const handProgressDesc = row => {
      progressDesc.value = row.currentProgress;
      ElMessageBox.prompt("", "项目阶段", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: progressDesc.value,
        // inputPlaceholder: "请填写变更申请原因",
        inputType: "textarea",
        inputValidator(value) {
          if (value == undefined) {
            return "内容不能为空";
          } else if (value.length == 0) {
            return "内容不能为空";
          } else if (value.length > 300) {
            return "请输入300个字符以内的内容";
          }
        },

        inputErrorMessage: "请输入变更申请原因"
      })
        .then(async ({ value }) => {
          const { code } = await updateProgress({
            projectId: row.id,
            progressDesc: value
          });
          if (code === 200) {
            row.currentProgress = value;
            NotifMessage.success(`更新成果`);
          }
        })
        .catch(err => {
          console.log(err);
        });
    };

    const initProjectTypeList = async () => {
      try {
        const params = {
          dicType: "rd_project_type"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          projectTypeArr.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };
    // 审批状态
    const initFlowStatusList = async () => {
      try {
        const params = {
          dicType: "rd_flow_status"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          flowStatusArr.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };
    const alertMsg = row => {
      ElMessageBox.alert(row.ext9, "驳回信息");
    };

    const changeAuth = row => {
      if (row.stageStatus !== "0") {
        if (+row.stageStatus > 5) {
          return false;
        }
        return true;
      }
      return row.stageStatus === "0" && row.stageApproveStatus === "3";
    };

    // 清除表单，重置
    const handleReset = () => {
      formRef.value.resetFields();
      formInline.documentName = "";
      formInline.documentType = "";
      formInline.achievementType = "";
      formInline.expertName = "";
      formInline.costName = "";
      formInline.createTimeStrStart = "";
      formInline.createTimeStrEnd = "";
      state.createTime = "";
    };

    // 根据条件进行搜索
    const handleSearch = (): void => {
      getTableData();
    };

    const handleAdvancedSearch = () => {
      state.isSearch = !state.isSearch;
      if (!state.isSearch) {
        formInline.documentName = "";
        formInline.documentType = "";
        formInline.achievementType = "";
        formInline.expertName = "";
        formInline.costName = "";
      }
    };

    // 删除记录
    const handleDelete = async item => {
      try {
        const { code, message } = await postProjectDelete({ id: item.id });
        if (code === 200) {
          NotifMessage.success(`${message}`);
          getTableData();
        } else {
          NotifMessage.error(`${message}`);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 创建项目
    const handleAdd = (): void => {
      router.push({
        path: "/project/create",
        query: { mode: "add" }
      });
    };

    // 更改项目
    const handleChange = (row): void => {
      router.push({
        path: "/project/create",
        query: { id: row.id, mode: "change" }
      });
      // state.changeDialogFormVisible = true;
      // state.target = row;
    };
    // 更改项目
    const handleStop = (row): void => {
      state.stopDialogFormVisible = true;
      state.target = row;
      state.projectId = row.id;
    };

    const submitStop = async stopInfo => {
      asyncStopMethod(stopInfo);
    };

    const asyncStopMethod = async (stopInfo: any): Promise<any> => {
      try {
        const projectChangeParamDTO = Object.assign({}, stopInfo);
        projectChangeParamDTO["alterationSignRecord"] = JSON.stringify(
          stopInfo.alterationSignRecord
        );
        projectChangeParamDTO["otherFile"] = JSON.stringify(stopInfo.otherFile);

        const { code, message } = await postProjecStop({
          id: state.projectId,
          reason: "",
          projectChangeParamDTO
        });
        if (code === 200) {
          state.stopDialogFormVisible = false;
          getTableData();
          NotifMessage.success(message);
        }
      } catch (err) {
        console.error(err);
      }
    };

    // 项目详情
    const handleLook = (row): void => {
      router.push({
        path: "/project/detail",
        query: {
          id: row.id,
          mode: "look",
          flowId: row.flowId,
          taskId: row.curTaskId,
          instanceId: row.instanceId,
          nodeId:
            row.nodeStatusJdCode && row.nodeStatusJdCode.toLocaleUpperCase(),
          isSkipYs: row.isSkipYs
        }
      });
    };

    const handleEdit = (row, type): void => {
      const cantype = row.canProcess === 1 && row.saveStatus === "3" ? 1 : 2;
      router.push({
        path: "/project/create",
        query: {
          id: row.id,
          mode: type,
          cantype,
          flowId: row.flowId,
          taskId: row.curTaskId,
          instanceId: row.instanceId,
          nodeId:
            row.nodeStatusJdCode && row.nodeStatusJdCode.toLocaleUpperCase(),
          isSkipYs: row.isSkipYs
        }
      });
    };

    const formatterStatusType2 = row => {
      return ProjectStatusMap2.get(row.stageApproveStatus);
    };
    const formatterStatusType = row => {
      if (row.stageStatus === "6") {
        return "已审核";
      } else {
        return ProjectStatusMap2.get(row.projectApproveStatus);
      }
    };

    const initProjectStageList = async () => {
      try {
        const params = {
          dicType: "rd_project_stage"
        };
        const { code, data } = await postDictList(params);
        if (code === 200) {
          projectStep.value = data;

          // projectStage.value = projectStep.value.map(el => el.dicCode);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const getAtch = row => {
      if (
        row.stageStatus === "0" &&
        row.canAuth === 1 &&
        row.saveStatus === "2"
      ) {
        return true;
      }

      if (
        row.stageStatus === "0" &&
        row.canProcess === 1 &&
        row.saveStatus === "3" &&
        row.stageApproveStatus === "2"
      ) {
        return true;
      }

      if (
        row.stageStatus === "0" &&
        (row.stageApproveStatus === "4" || row.stageApproveStatus === "1") &&
        row.canAuth === 1
      ) {
        return true;
      }
      return false;
    };

    const getProjectStage = row => {
      console.log(row.projectStage);
      if (row.projectStage) {
        return "";
      }
      // const projectStage = JSON.parse(row.projectStage);
      let str = "";
      // projectStage.forEach(el => {
      //   const target = projectStep.value.find(obj => el === obj.dicCode);
      //   if (target) {
      //     str += target.dicValue + " ";
      //   }
      // });
      return str;
    };

    // 请求数据
    initProjectStageList();
    getTableData();
    initProjectTypeList();
    initFlowStatusList();
    return {
      getEditAuth,
      getChangeAuth,
      handleChangeDate,
      formatterStatusType2,
      changeAuth,
      handProgressDesc,
      projectStep,
      getProjectStage,
      projectTypeArr,
      flowStatusArr,
      loading,
      formInline,
      formRef,
      total,
      ...toRefs(state),
      handleAdd,
      handleReset,
      handleSearch,
      handleDelete,
      handleLook,
      handleEdit,
      handleChange,
      handleStop,
      formatterStatusType,
      alertMsg,
      submitStop,
      handleAdvancedSearch,
      getAtch
    };
  }
});
</script>
